package com.nepu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nepu.gmall.realtime.bean.TradePaymentWindowBean;
import com.nepu.gmall.realtime.util.ClickHouseUtil;
import com.nepu.gmall.realtime.util.DateFormatUtil;
import com.nepu.gmall.realtime.util.KafkaUtils;
import com.nepu.gmall.realtime.util.TimestampLtz3CompareUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 *
 * 交易域支付各窗口汇总表
 * 从 Kafka 读取交易域支付成功主题数据，统计支付成功独立用户数和首次支付成功用户数。
 * （1）首先从kafka的dwd_trade_pay_detail_suc主题中读取到支付成功的数据
 * （2）转换数据结构为json，同时过滤掉非json的数据
 * （3）根据order_detail_id对数据进行分组。
 * （4）过滤由于left join 产生的重复数据，保留最后到来的数据，这里需要使用到定时器
 * （5）提取事件时间，生成watermark
 * （6）按照用户id对数据进行分组
 * （7）根据状态计算出支付成功用户数和首次支付成功用户数
 * （8）开窗聚合
 * （9）将数据写入到ClickHouse
 * （10）执行
 *
 * 数据的流向
 *                                                             mock --> mysql --> maxwell --> kafka(topic_db)\
 * mock --> mysql --> maxwell --> kafka(topic_db) --> DwdTradeOrderPreProcess.class --> DwdTradeOrderDetail -->DwdTradePayDetailSuc.class --> DwsTradePaymentSucWindow.class -->clickHouse
 * @author chenshuaijun
 * @create 2023-03-03 10:23
 */
public class DwsTradePaymentSucWindow {

    public static void main(String[] args) throws Exception {

        // TODO 1、创建执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // 生产环境下是一定不会将任务的并行度设置为1的，这里具体的设置是和我们等下要读取的kafka的相应的主题的分区的个数相同
        env.setParallelism(1);
        // 设置checkpoint的信息：设置checkpoint的间隔是5分钟,并且checkpoint的级别是精确一次性
        /*env.enableCheckpointing(5 * 60000L, CheckpointingMode.EXACTLY_ONCE);
        // 设置checkpoint的超时时间是10分钟
        env.getCheckpointConfig().setCheckpointTimeout(10 * 60000L);
        // 设置外部检查点。可以将检查点的元数据信息定期写入外部系统，这样当job失败时，检查点不会被清除。这样如果job失败，可以从检查点恢复job。
        env.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        // 设置checkpoint的重启的策略
        env.setRestartStrategy(RestartStrategies.failureRateRestart(10, Time.of(1L, TimeUnit.DAYS), Time.of(3L, TimeUnit.MINUTES)));
        // 设置两个checkpoint之间的最小的间隔时间
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
        // 设置状态后端: 设置状态后端为内存级别
        env.setStateBackend(new HashMapStateBackend());
        // 设置checkpoint的存储的路径
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/checkpoint");
        // 因为我们的HDFS只有atguigu用户才能够操作，所以要将用户设置为atguigu
        System.setProperty("HADOOP_USER_NAME", "atguigu");*/
        // TODO 2、从kafka中读取支付成功的数据
        String topic = "dwd_trade_pay_detail_suc";
        DataStreamSource<String> dwsTradePaymentSucDS = env.addSource(KafkaUtils.getKafkaConsumer(topic, "DwsTradePaymentSucWindow"));
        // TODO 3、转换数据结构
        SingleOutputStreamOperator<JSONObject> transformTypeDS = dwsTradePaymentSucDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                try {
                    JSONObject jsonObject = JSON.parseObject(value);
                    out.collect(jsonObject);
                } catch (Exception e) {
                    System.out.println("数据不是json格式：" + value);
                }
            }
        });
        // TODO 4、将数据按照order_detail_id进行分组
        KeyedStream<JSONObject, String> orderDetailIdDS = transformTypeDS.keyBy(json -> json.getString("order_detail_id"));
        // TODO 5、按照状态对数据进行过滤 --> 我们要保留的是最后一条数据，如果
        SingleOutputStreamOperator<JSONObject> filterDetailDS = orderDetailIdDS.process(new KeyedProcessFunction<String, JSONObject, JSONObject>() {

            private ValueState<JSONObject> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                valueState = getRuntimeContext().getState(new ValueStateDescriptor<JSONObject>("value-statue", JSONObject.class));
            }

            @Override
            public void processElement(JSONObject value, Context ctx, Collector<JSONObject> out) throws Exception {
                // 首先取出状态
                JSONObject state = valueState.value();

                if (state == null) {
                    // 如果为null，就更新状态并且  设置定时器
                    valueState.update(value);
                    ctx.timerService().registerProcessingTimeTimer(ctx.timerService().currentProcessingTime() + 5000L);

                } else {
                    String stateDate = state.getString("row_op_ts");
                    String currentDate = value.getString("row_op_ts");
                    int compare = TimestampLtz3CompareUtil.compare(stateDate, currentDate);
                    if (compare != 1) {
                        valueState.update(value);
                    }
                }
            }

            @Override
            public void onTimer(long timestamp, OnTimerContext ctx, Collector<JSONObject> out) throws Exception {
                // 定时器时间到了之后，输出状态中的数据，清空状态
                out.collect(valueState.value());
                valueState.clear();
            }
        });

        // TODO 6、提取时间时间生成watermark
        SingleOutputStreamOperator<JSONObject> watermarkDS = filterDetailDS.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject element, long recordTimestamp) {
                return DateFormatUtil.toTs(element.getString("callback_time"), true);
            }
        }));
        // TODO 7、根据用户ID对数据进行分组
        KeyedStream<JSONObject, String> userIdKeyedDS = watermarkDS.keyBy(json -> json.getString("user_id"));
        // TODO 8、根据状态进行过滤
        SingleOutputStreamOperator<TradePaymentWindowBean> flatMapFilterDS = userIdKeyedDS.flatMap(new RichFlatMapFunction<JSONObject, TradePaymentWindowBean>() {

            private ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                valueState = getRuntimeContext().getState(new ValueStateDescriptor<String>("last-pay", String.class));
            }

            @Override
            public void flatMap(JSONObject value, Collector<TradePaymentWindowBean> out) throws Exception {
                // 先取出状态中的数据
                String state = valueState.value();
                // 取出时间
                String currentDate = value.getString("callback_time").split(" ")[0];
                // 支付成功独立用户数
                long paymentSucUniqueUserCount = 0;
                // 支付成功新用户数
                long paymentSucNewUserCount = 0;

                if (state == null) {
                    paymentSucUniqueUserCount = 1;
                    paymentSucNewUserCount = 1;
                    valueState.update(currentDate);
                } else if (!state.equals(currentDate)) {
                    paymentSucUniqueUserCount = 1;
                    valueState.update(currentDate);
                }

                if (paymentSucUniqueUserCount == 1) {
                    out.collect(new TradePaymentWindowBean("", "", paymentSucUniqueUserCount, paymentSucNewUserCount, null));
                }
            }
        });
        // TODO 9、开窗聚合
        SingleOutputStreamOperator<TradePaymentWindowBean> reslutDs = flatMapFilterDS.windowAll(TumblingProcessingTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<TradePaymentWindowBean>() {
                    @Override
                    public TradePaymentWindowBean reduce(TradePaymentWindowBean value1, TradePaymentWindowBean value2) throws Exception {
                        value1.setPaymentSucUniqueUserCount(value1.getPaymentSucUniqueUserCount() + value2.getPaymentSucUniqueUserCount());
                        value1.setPaymentSucNewUserCount(value1.getPaymentSucNewUserCount() + value2.getPaymentSucNewUserCount());
                        return value1;
                    }
                }, new AllWindowFunction<TradePaymentWindowBean, TradePaymentWindowBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<TradePaymentWindowBean> values, Collector<TradePaymentWindowBean> out) throws Exception {
                        TradePaymentWindowBean tradePaymentWindowBean = values.iterator().next();

                        tradePaymentWindowBean.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                        tradePaymentWindowBean.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                        tradePaymentWindowBean.setTs(System.currentTimeMillis());

                        out.collect(tradePaymentWindowBean);
                    }
                });

        // TODO 10将数据写出到clickhouse
        reslutDs.print(">>>>");
        reslutDs.addSink(ClickHouseUtil.getJdbcSink("insert into dws_trade_payment_suc_window values(?,?,?,?,?)"));

        // TODO 11、执行
        env.execute("DwsTradePaymentSucWindow");
    }
}
